import { BaseComponents, IconFont } from "@/components";
import { View } from "@tarojs/components";
import Taro from "@tarojs/taro";
import { iconType } from "@/components/IconFont";
import { rpx2px } from "@/utils";

import styles from "./index.module.scss";

export const NAV_BAR_HEIGHT =
  rpx2px(88) + Taro.getSystemInfoSync().statusBarHeight;

export interface Props {
  title: string;
  titleStyle?: React.CSSProperties;
  icon: iconType;
  visibleIcon: boolean;
  iconStyle?: React.CSSProperties;
  back?: () => void;
  // 最外层 常用于设置 backgroundColor & backgroundImage
  style?: React.CSSProperties;
}
export const defaultProps: Props = {
  title: "",
  icon: "iconicon_nav_back_18",
  visibleIcon: false,
};

interface State {
  statusBarHeight: number;
}

class NavBar extends BaseComponents<Props, State> {
  static defaultProps: Props = {
    ...defaultProps,
  };

  constructor(props: Props) {
    super(props);

    this.state = {
      statusBarHeight: 0,
    };
  }

  componentDidMount() {
    this.init();
  }

  init = () => {
    Taro.getSystemInfo().then((res) => {
      const staBarH = res.statusBarHeight;
      // console.log(staBarH);
      this.setState({
        statusBarHeight: staBarH,
      });
    });
  };

  back = () => {
    const { back } = this.props;
    if (typeof back === "function") {
      return back();
    }

    const pages = Taro.getCurrentPages();

    if (pages.length === 1) {
      return Taro.switchTab({ url: "/pages/index/index" });
    }

    Taro.navigateBack();
  };



  render() {
    const {
      icon,
      title,
      visibleIcon,
      iconStyle,
      style,
      titleStyle,
    } = this.props;
    const { statusBarHeight } = this.state;

    return (
      <View
        style={{
          height: NAV_BAR_HEIGHT,
          flexBasis: NAV_BAR_HEIGHT,
        }}
      >
        <View className={styles.navBar} style={style}>
          <View
            className={styles.statusBarHeight}
            style={{
              height: statusBarHeight,
            }}
          ></View>
          <View className={styles.navBarMain}>
            <View className={styles.left} style={iconStyle}>
              {visibleIcon && (
                <View className={styles.leftContariner} onClick={this.back}>
                  <IconFont icon={icon}></IconFont>
                </View>
              )}
            </View>
            <View className={styles.center} style={titleStyle}>
              {title}
            </View>
            <View className={styles.right}></View>
          </View>
        </View>
      </View>
    );
  }
}

export default NavBar;
